package cn.itsource.config;

import cn.itsource.utils.AjaxResult;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisService redisService;

    /*
        如果这个方法，返回了一个false，那么此次请求直接结束，而且 不再执行 postHandler()和afterCompletion（）

        因为在所有请求，除了被放行的请求之外，其他请求，都会先经过这里，校验token是否存在
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>preHandle");
        //在request请求中，我们可以拿到前端携带的所有参数，就可以在参数中，判断token是否存在
        //在java-web开发中，令牌token一般不作为param参数传递，而是放在header头信息中
        //如何在request中获取header头信息中？？
        String token = request.getHeader("token");
        String keyObjectValue = redisService.getKeyObjectValue(token, String.class);

        if (StringUtils.isAnyBlank(token, keyObjectValue)) {
            response.setContentType("text/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSONObject.toJSONString(AjaxResult.error().setMessage("noLogin")));
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println(">>>>>>>>>>>>>>>>>>>>>>postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println(">>>>>>>>>>>>>>>>>>>>>>afterCompletion");
    }
}
